package com.newlink.building.common_base.utils

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment

/**
 * 增强版权限管理工具
 * @Author: Enhanced by Claude
 * @Date: 2025-09-15
 * @Description: 现代化权限请求和管理工具，支持链式调用和批量处理
 */
object PermissionHelperEnhanced {

    /**
     * 权限组枚举
     */
    enum class PermissionGroup {
        CAMERA, STORAGE, LOCATION, MICROPHONE, PHONE, CONTACTS, SMS, CALENDAR, SENSORS, NOTIFICATION
    }

    /**
     * 权限请求结果
     */
    data class PermissionResult(
        val permission: String,
        val isGranted: Boolean,
        val shouldShowRationale: Boolean = false
    )

    /**
     * 权限组结果
     */
    data class PermissionGroupResult(
        val group: PermissionGroup,
        val results: List<PermissionResult>,
        val allGranted: Boolean
    ) {
        val grantedPermissions: List<String> get() = results.filter { it.isGranted }.map { it.permission }
        val deniedPermissions: List<String> get() = results.filter { !it.isGranted }.map { it.permission }
    }

    /**
     * 权限请求回调
     */
    interface PermissionCallback {
        fun onPermissionGranted(permission: String) {}
        fun onPermissionDenied(permission: String, shouldShowRationale: Boolean) {}
        fun onPermissionGroupResult(result: PermissionGroupResult) {}
        fun onAllPermissionsGranted(permissions: List<String>) {}
        fun onSomePermissionsDenied(granted: List<String>, denied: List<String>) {}
    }

    // ========== 权限组映射 ==========

    /**
     * 获取权限组对应的权限列表
     */
    fun getPermissionsForGroup(group: PermissionGroup): List<String> {
        return when (group) {
            PermissionGroup.CAMERA -> listOf(Manifest.permission.CAMERA)

            PermissionGroup.STORAGE -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                listOf(
                    Manifest.permission.READ_MEDIA_IMAGES,
                    Manifest.permission.READ_MEDIA_VIDEO,
                    Manifest.permission.READ_MEDIA_AUDIO
                )
            } else {
                listOf(
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
            }

            PermissionGroup.LOCATION -> listOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )

            PermissionGroup.MICROPHONE -> listOf(Manifest.permission.RECORD_AUDIO)

            PermissionGroup.PHONE -> listOf(
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.CALL_PHONE,
                Manifest.permission.READ_CALL_LOG
            )

            PermissionGroup.CONTACTS -> listOf(
                Manifest.permission.READ_CONTACTS,
                Manifest.permission.WRITE_CONTACTS
            )

            PermissionGroup.SMS -> listOf(
                Manifest.permission.SEND_SMS,
                Manifest.permission.READ_SMS,
                Manifest.permission.RECEIVE_SMS
            )

            PermissionGroup.CALENDAR -> listOf(
                Manifest.permission.READ_CALENDAR,
                Manifest.permission.WRITE_CALENDAR
            )

            PermissionGroup.SENSORS -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
                listOf(Manifest.permission.BODY_SENSORS)
            } else {
                emptyList()
            }

            PermissionGroup.NOTIFICATION -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                listOf(Manifest.permission.POST_NOTIFICATIONS)
            } else {
                emptyList()
            }
        }
    }

    // ========== 权限检查 ==========

    /**
     * 检查单个权限
     */
    fun hasPermission(context: Context, permission: String): Boolean {
        return try {
            ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
        } catch (e: Exception) {
            EnhancedLogger.e("PermissionHelper", "检查权限失败: $permission", e)
            false
        }
    }

    /**
     * 检查多个权限
     */
    fun hasPermissions(context: Context, permissions: List<String>): Map<String, Boolean> {
        return permissions.associateWith { hasPermission(context, it) }
    }

    /**
     * 检查权限组
     */
    fun hasPermissionGroup(context: Context, group: PermissionGroup): PermissionGroupResult {
        val permissions = getPermissionsForGroup(group)
        val results = permissions.map { permission ->
            PermissionResult(
                permission = permission,
                isGranted = hasPermission(context, permission)
            )
        }

        return PermissionGroupResult(
            group = group,
            results = results,
            allGranted = results.all { it.isGranted }
        )
    }

    /**
     * 检查所有权限是否已授予
     */
    fun areAllPermissionsGranted(context: Context, permissions: List<String>): Boolean {
        return permissions.all { hasPermission(context, it) }
    }

    // ========== 权限请求建造者 ==========

    /**
     * 权限请求建造者类
     */
    class PermissionRequestBuilder {
        private val permissions = mutableSetOf<String>()
        private val permissionGroups = mutableSetOf<PermissionGroup>()
        private var callback: PermissionCallback? = null
        private var rationaleTitle: String = "需要权限"
        private var rationaleMessage: String = "应用需要这些权限才能正常工作"
        private var showSettingsDialog: Boolean = true
        private var settingsTitle: String = "权限设置"
        private var settingsMessage: String = "请在设置中手动开启权限"

        /**
         * 添加单个权限
         */
        fun permission(permission: String): PermissionRequestBuilder {
            permissions.add(permission)
            return this
        }

        /**
         * 添加多个权限
         */
        fun permissions(vararg permissions: String): PermissionRequestBuilder {
            this.permissions.addAll(permissions)
            return this
        }

        /**
         * 添加权限组
         */
        fun permissionGroup(group: PermissionGroup): PermissionRequestBuilder {
            permissionGroups.add(group)
            return this
        }

        /**
         * 设置回调
         */
        fun callback(callback: PermissionCallback): PermissionRequestBuilder {
            this.callback = callback
            return this
        }

        /**
         * 设置权限说明对话框
         */
        fun rationale(title: String, message: String): PermissionRequestBuilder {
            this.rationaleTitle = title
            this.rationaleMessage = message
            return this
        }

        /**
         * 设置设置页面对话框
         */
        fun settings(title: String, message: String): PermissionRequestBuilder {
            this.settingsTitle = title
            this.settingsMessage = message
            return this
        }

        /**
         * 是否显示设置对话框
         */
        fun showSettingsDialog(show: Boolean): PermissionRequestBuilder {
            this.showSettingsDialog = show
            return this
        }

        /**
         * 执行权限请求
         */
        fun request(activity: AppCompatActivity) {
            // 收集所有权限
            val allPermissions = mutableSetOf<String>()
            allPermissions.addAll(permissions)
            permissionGroups.forEach { group ->
                allPermissions.addAll(getPermissionsForGroup(group))
            }

            if (allPermissions.isEmpty()) {
                EnhancedLogger.w("PermissionHelper", "没有需要请求的权限")
                return
            }

            // 创建权限请求器
            val permissionRequester = PermissionRequester(
                activity = activity,
                permissions = allPermissions.toList(),
                callback = callback,
                rationaleTitle = rationaleTitle,
                rationaleMessage = rationaleMessage,
                showSettingsDialog = showSettingsDialog,
                settingsTitle = settingsTitle,
                settingsMessage = settingsMessage
            )

            permissionRequester.requestPermissions()
        }
    }

    // ========== 权限请求器 ==========

    /**
     * 权限请求器
     */
    private class PermissionRequester(
        private val activity: AppCompatActivity,
        private val permissions: List<String>,
        private val callback: PermissionCallback?,
        private val rationaleTitle: String,
        private val rationaleMessage: String,
        private val showSettingsDialog: Boolean,
        private val settingsTitle: String,
        private val settingsMessage: String
    ) {

        private lateinit var permissionLauncher: ActivityResultLauncher<Array<String>>

        init {
            registerPermissionLauncher()
        }

        private fun registerPermissionLauncher() {
            permissionLauncher = activity.registerForActivityResult(
                ActivityResultContracts.RequestMultiplePermissions()
            ) { results ->
                handlePermissionResults(results)
            }
        }

        fun requestPermissions() {
            // 检查当前权限状态
            val permissionStatus = permissions.associateWith { permission ->
                hasPermission(activity, permission)
            }

            val deniedPermissions = permissionStatus.filter { !it.value }.keys.toList()

            if (deniedPermissions.isEmpty()) {
                // 所有权限已授予
                EnhancedLogger.i("PermissionHelper", "所有权限已授予: $permissions")
                callback?.onAllPermissionsGranted(permissions)
                return
            }

            // 检查是否需要显示权限说明
            val shouldShowRationale = deniedPermissions.any { permission ->
                activity.shouldShowRequestPermissionRationale(permission)
            }

            if (shouldShowRationale) {
                showPermissionRationale(deniedPermissions)
            } else {
                requestPermissionsDirectly(deniedPermissions)
            }
        }

        private fun showPermissionRationale(deniedPermissions: List<String>) {
            // 这里可以显示自定义对话框解释权限用途
            // 为了简化，直接请求权限
            requestPermissionsDirectly(deniedPermissions)
        }

        private fun requestPermissionsDirectly(deniedPermissions: List<String>) {
            EnhancedLogger.i("PermissionHelper", "请求权限: $deniedPermissions")
            permissionLauncher.launch(deniedPermissions.toTypedArray())
        }

        private fun handlePermissionResults(results: Map<String, Boolean>) {
            val granted = mutableListOf<String>()
            val denied = mutableListOf<String>()

            results.forEach { (permission, isGranted) ->
                if (isGranted) {
                    granted.add(permission)
                    callback?.onPermissionGranted(permission)
                } else {
                    denied.add(permission)
                    val shouldShowRationale = activity.shouldShowRequestPermissionRationale(permission)
                    callback?.onPermissionDenied(permission, shouldShowRationale)
                }
            }

            // 记录结果
            EnhancedLogger.i("PermissionHelper", "权限请求结果 - 已授予: $granted, 被拒绝: $denied")

            if (denied.isEmpty()) {
                callback?.onAllPermissionsGranted(granted)
            } else {
                callback?.onSomePermissionsDenied(granted, denied)

                // 是否显示设置对话框
                if (showSettingsDialog) {
                    showSettingsDialog(denied)
                }
            }
        }

        private fun showSettingsDialog(deniedPermissions: List<String>) {
            // 这里可以显示引导用户到设置页面的对话框
            // 为了简化，直接打开应用设置页面
            openAppSettings(activity)
        }
    }

    // ========== 便捷方法 ==========

    /**
     * 创建权限请求建造者
     */
    fun with(activity: AppCompatActivity): PermissionRequestBuilder {
        return PermissionRequestBuilder()
    }

    /**
     * 请求相机权限
     */
    fun requestCamera(activity: AppCompatActivity, callback: PermissionCallback? = null) {
        with(activity)
            .permissionGroup(PermissionGroup.CAMERA)
            .rationale("相机权限", "需要相机权限来拍照")
            .callback(callback ?: object : PermissionCallback {})
            .request(activity)
    }

    /**
     * 请求存储权限
     */
    fun requestStorage(activity: AppCompatActivity, callback: PermissionCallback? = null) {
        with(activity)
            .permissionGroup(PermissionGroup.STORAGE)
            .rationale("存储权限", "需要存储权限来保存文件")
            .callback(callback ?: object : PermissionCallback {})
            .request(activity)
    }

    /**
     * 请求位置权限
     */
    fun requestLocation(activity: AppCompatActivity, callback: PermissionCallback? = null) {
        with(activity)
            .permissionGroup(PermissionGroup.LOCATION)
            .rationale("位置权限", "需要位置权限来获取当前位置")
            .callback(callback ?: object : PermissionCallback {})
            .request(activity)
    }

    /**
     * 请求录音权限
     */
    fun requestMicrophone(activity: AppCompatActivity, callback: PermissionCallback? = null) {
        with(activity)
            .permissionGroup(PermissionGroup.MICROPHONE)
            .rationale("录音权限", "需要录音权限来录制音频")
            .callback(callback ?: object : PermissionCallback {})
            .request(activity)
    }

    /**
     * 请求通知权限（Android 13+）
     */
    fun requestNotification(activity: AppCompatActivity, callback: PermissionCallback? = null) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            with(activity)
                .permissionGroup(PermissionGroup.NOTIFICATION)
                .rationale("通知权限", "需要通知权限来显示重要消息")
                .callback(callback ?: object : PermissionCallback {})
                .request(activity)
        } else {
            callback?.onAllPermissionsGranted(emptyList())
        }
    }

    // ========== 工具方法 ==========

    /**
     * 打开应用设置页面
     */
    fun openAppSettings(context: Context) {
        try {
            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                data = Uri.fromParts("package", context.packageName, null)
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            context.startActivity(intent)
            EnhancedLogger.i("PermissionHelper", "打开应用设置页面")
        } catch (e: Exception) {
            EnhancedLogger.e("PermissionHelper", "打开设置页面失败", e)
            ToastUtilsEnhanced.showError("无法打开设置页面")
        }
    }

    /**
     * 获取权限友好名称
     */
    fun getPermissionName(permission: String): String {
        return when (permission) {
            Manifest.permission.CAMERA -> "相机"
            Manifest.permission.READ_EXTERNAL_STORAGE -> "读取存储"
            Manifest.permission.WRITE_EXTERNAL_STORAGE -> "写入存储"
            Manifest.permission.ACCESS_FINE_LOCATION -> "精确位置"
            Manifest.permission.ACCESS_COARSE_LOCATION -> "大概位置"
            Manifest.permission.RECORD_AUDIO -> "录音"
            Manifest.permission.READ_PHONE_STATE -> "读取手机状态"
            Manifest.permission.CALL_PHONE -> "拨打电话"
            Manifest.permission.READ_CONTACTS -> "读取联系人"
            Manifest.permission.WRITE_CONTACTS -> "写入联系人"
            Manifest.permission.POST_NOTIFICATIONS -> "通知"
            else -> permission.substringAfterLast(".")
        }
    }

    /**
     * 记录权限状态
     */
    fun logPermissionStatus(context: Context, permissions: List<String>) {
        val message = buildString {
            appendLine("🔐 权限状态检查")
            appendLine("┌─────────────────────────────────────")
            permissions.forEach { permission ->
                val status = if (hasPermission(context, permission)) "✅ 已授予" else "❌ 未授予"
                val name = getPermissionName(permission)
                appendLine("│ $name: $status")
            }
            append("└─────────────────────────────────────")
        }

        EnhancedLogger.i("PermissionHelper", message)
    }
}